package com.service.atm;

import java.io.UnsupportedEncodingException;

import com.bpms.common.CommonUtil;
import com.bpms.common.VO;
import com.bpms.common.VOList;
import com.bpms.esb.IService;
import com.bpms.esb.SV;

public class Answer_atm_account implements IService {

	public static void main(String[] args) { // test
		VO vo = new VO();
		vo.setAttr("CARDID", "123456");
		vo.setAttr("ACCOUNTTYPE", "1");
		vo.setAttr("PASSWORD", "123");
		VO result = new Answer_atm_account().exec(vo);
		CommonUtil.debug(result);
	}

	public VO exec(VO args) {
		CommonUtil.debug("Answer_atm_account begin");
		try {
			VO result = SV.g("khqy.Getavailableaccounts", args);
			
				return packResult((VOList) result.getObj("volist"));
			
		} catch (Exception e) {
			CommonUtil.debug("Answer_atm_account  error", e);
			return null;
		}
	}

	private VO packResult(VOList args) {
		VO vo = new VO();
		// R001 处理结果代码 0000:成功
		// R002 结果描述
		// R003 账号数量
		// R004 主帐号名
		// T001 第一个账号
		// T002 第二个账号
		// T N 第N个账号

		String message = "" + args.rowCount;
		message = ""; // 本报文长度 u_char[8]
		message += "00000000"; // 流水号 U_char[8]
		message += "00000000"; // 交易报文总长度 U_char[8] I
		message += "95pj";// 交易码 u_char[4]
		message += "0000";// 应答结果 u_char[4]
		String accountname = "";
		if ((args != null) && (args.rowCount > 0)) {
			message += "00000004" + "R001" + "0000";
			message += "00000006" + "R002" + "sucess";
			message += "00000004" + "R003" + String.format("%04d", args.rowCount);
			for (int i = 1; i <= args.rowCount; i++) {
				String a = ((VO) args.listData.get(i - 1)).getAttr("ACCOUNT");
				message += String.format("%08d", a.toString().length()) + "T" + String.format("%03d", i) + a;
				accountname = ((VO) args.listData.get(i - 1)).getAttr("FULLNAME");
			}
		} else {
			try {
				message += "00000004" + "R001" + "9999";
				// message += "00000006"+"R002"+"faild";
				String error = "帐户不存在或密码错误";
				message += String.format("%08d", error.getBytes("gb2312").length) + "R002" + error;
				message += "00000004R003" + String.format("%020d", 0);
				message += "00000004" + "R003" + String.format("%04d", 0);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		try {
			message += String.format("%08d", accountname.getBytes("gb2312").length) + "R004" + accountname; // 账户名
			// message = String.format("%08d", message.length()) + message; //报文长度

		
			message = String.format("%08d", message.getBytes("gb2312").length) + message;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		CommonUtil.debug(message);
		vo.setAttr("msg", message);
		CommonUtil.debug("Answer_atm_account packResult done");
		return vo;
	}
}
